import { Inventory, InventoryItem } from '@/player/Inventory';
import { getBlock } from '@/blocks/BlockRegistry';

export class InventoryUI {
  private inventory: Inventory;
  private hotbarElement!: HTMLElement;
  private fullInventoryElement!: HTMLElement;
  private isVisible = true;
  private isFullInventoryOpen = false;
  private draggedItem: { item: InventoryItem; sourceIndex: number } | null = null;
  private dragElement: HTMLElement | null = null;

  constructor(inventory: Inventory) {
    this.inventory = inventory;
    this.createHotbar();
    this.createFullInventory();
    this.setupEventListeners();
  }

  private createHotbar(): void {
    this.hotbarElement = document.createElement('div');
    this.hotbarElement.id = 'hotbar';
    this.hotbarElement.style.cssText = `
      position: fixed;
      bottom: 20px;
      left: 50%;
      transform: translateX(-50%);
      display: flex;
      gap: 2px;
      z-index: 1000;
      background: rgba(0, 0, 0, 0.5);
      padding: 5px;
      border-radius: 5px;
    `;

    for (let i = 0; i < 9; i++) {
      const slot = document.createElement('div');
      slot.className = 'hotbar-slot';
      slot.style.cssText = `
        width: 40px;
        height: 40px;
        background: #333;
        border: 2px solid #666;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 12px;
        font-weight: bold;
        position: relative;
        cursor: pointer;
      `;

      slot.addEventListener('click', () => {
        this.inventory.setSelectedSlot(i);
        this.updateHotbar();
      });

      this.hotbarElement.appendChild(slot);
    }

    document.body.appendChild(this.hotbarElement);
    this.updateHotbar();
  }

  public updateHotbar(): void {
    const hotbarItems = this.inventory.getHotbarItems();
    const selectedSlot = this.inventory.getSelectedSlot();
    
    Array.from(this.hotbarElement.children).forEach((slot, index) => {
      const slotElement = slot as HTMLElement;
      const item = hotbarItems[index];
      
      if (item) {
        const block = getBlock(item.type);
        slotElement.innerHTML = `
          <div style="font-size: 10px; text-align: center;">
            ${block.name}<br>
            <span style="font-size: 8px;">${item.count}</span>
          </div>
        `;
      } else {
        slotElement.innerHTML = '';
      }
      
      if (index === selectedSlot) {
        slotElement.style.border = '2px solid #fff';
        slotElement.style.background = '#555';
      } else {
        slotElement.style.border = '2px solid #666';
        slotElement.style.background = '#333';
      }
    });
  }

  public show(): void {
    this.hotbarElement.style.display = 'flex';
    this.isVisible = true;
  }

  public hide(): void {
    this.hotbarElement.style.display = 'none';
    this.isVisible = false;
  }

  public toggle(): void {
    if (this.isVisible) {
      this.hide();
    } else {
      this.show();
    }
  }

  private createFullInventory(): void {
    this.fullInventoryElement = document.createElement('div');
    this.fullInventoryElement.id = 'full-inventory';
    this.fullInventoryElement.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 400px;
      height: 300px;
      background: rgba(0, 0, 0, 0.9);
      border: 2px solid #666;
      border-radius: 10px;
      padding: 20px;
      z-index: 2000;
      display: none;
      flex-direction: column;
    `;

    // 创建标题
    const title = document.createElement('div');
    title.textContent = 'Inventory';
    title.style.cssText = `
      color: white;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 15px;
      text-align: center;
    `;
    this.fullInventoryElement.appendChild(title);

    // 创建主物品栏区域（27个槽位，3x9）
    const mainInventory = document.createElement('div');
    mainInventory.className = 'main-inventory';
    mainInventory.style.cssText = `
      display: grid;
      grid-template-columns: repeat(9, 1fr);
      grid-template-rows: repeat(3, 1fr);
      gap: 2px;
      margin-bottom: 10px;
    `;

    // 创建27个主物品栏槽位（槽位9-35）
    for (let i = 9; i < 36; i++) {
      const slot = this.createInventorySlot(i);
      mainInventory.appendChild(slot);
    }

    this.fullInventoryElement.appendChild(mainInventory);

    // 创建快捷栏区域（9个槽位）
    const hotbarSection = document.createElement('div');
    hotbarSection.className = 'hotbar-section';
    hotbarSection.style.cssText = `
      display: grid;
      grid-template-columns: repeat(9, 1fr);
      gap: 2px;
      margin-top: 10px;
      border-top: 1px solid #666;
      padding-top: 10px;
    `;

    // 创建9个快捷栏槽位（槽位0-8）
    for (let i = 0; i < 9; i++) {
      const slot = this.createInventorySlot(i);
      hotbarSection.appendChild(slot);
    }

    this.fullInventoryElement.appendChild(hotbarSection);

    // 创建工具栏
    const toolbar = document.createElement('div');
    toolbar.style.cssText = `
      position: absolute;
      top: 10px;
      right: 10px;
      display: flex;
      gap: 5px;
    `;

    // 创建整理按钮
    const sortButton = document.createElement('button');
    sortButton.textContent = 'Sort';
    sortButton.style.cssText = `
      background: #4CAF50;
      color: white;
      border: none;
      padding: 5px 10px;
      border-radius: 3px;
      cursor: pointer;
      font-size: 12px;
    `;
    sortButton.addEventListener('click', () => this.sortInventory());
    toolbar.appendChild(sortButton);

    // 创建关闭按钮
    const closeButton = document.createElement('button');
    closeButton.textContent = 'Close';
    closeButton.style.cssText = `
      background: #666;
      color: white;
      border: none;
      padding: 5px 10px;
      border-radius: 3px;
      cursor: pointer;
      font-size: 12px;
    `;
    closeButton.addEventListener('click', () => this.closeFullInventory());
    toolbar.appendChild(closeButton);

    this.fullInventoryElement.appendChild(toolbar);

    document.body.appendChild(this.fullInventoryElement);
  }

  private createInventorySlot(index: number): HTMLElement {
    const slot = document.createElement('div');
    slot.className = 'inventory-slot';
    slot.dataset.slotIndex = index.toString();
    slot.style.cssText = `
      width: 35px;
      height: 35px;
      background: #333;
      border: 1px solid #666;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 10px;
      font-weight: bold;
      position: relative;
      cursor: pointer;
    `;

    // 添加事件监听器
    slot.addEventListener('click', (e) => this.handleSlotClick(e, index));
    slot.addEventListener('contextmenu', (e) => this.handleSlotRightClick(e, index));
    slot.addEventListener('mousedown', (e) => this.handleSlotMouseDown(e, index));
    slot.addEventListener('mouseup', (e) => this.handleSlotMouseUp(e, index));
    slot.addEventListener('mouseover', (e) => this.handleSlotMouseOver(e, index));
    slot.addEventListener('mouseleave', (e) => this.handleSlotMouseLeave(e, index));

    return slot;
  }

  private handleSlotClick(event: MouseEvent, slotIndex: number): void {
    event.preventDefault();
    
    // 如果点击的是快捷栏槽位，设置为选中
    if (slotIndex < 9) {
      this.inventory.setSelectedSlot(slotIndex);
      this.updateHotbar();
    }
    
    this.updateFullInventory();
  }

  private handleSlotRightClick(event: MouseEvent, slotIndex: number): void {
    event.preventDefault();
    
    // 右键点击功能：拆分物品堆（增强版）
    const item = this.inventory.getItem(slotIndex);
    if (item && item.count > 1) {
      const halfCount = Math.floor(item.count / 2);
      const remainingCount = item.count - halfCount;
      
      // 更新原槽位
      this.inventory.setItem(slotIndex, item.type, remainingCount);
      
      // 尝试在空槽位放置拆分的物品
      const result = this.inventory.addItemWithOverflow(item.type, halfCount);
      
      if (result.overflow > 0) {
        // 如果有溢出，恢复原状并显示提示
        this.inventory.setItem(slotIndex, item.type, item.count);
        this.showNotification('Inventory full! Cannot split stack.');
      } else {
        this.showNotification(`Split stack: ${remainingCount} + ${halfCount}`);
      }
      
      this.updateFullInventory();
      this.updateHotbar();
    }
  }

  private setupEventListeners(): void {
    // 监听ESC键关闭物品栏
    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape' && this.isFullInventoryOpen) {
        this.closeFullInventory();
      }
    });
  }

  public openFullInventory(): void {
    this.fullInventoryElement.style.display = 'flex';
    this.isFullInventoryOpen = true;
    this.updateFullInventory();
    
    // 暂停游戏（简化版）
    document.body.style.cursor = 'default';
  }

  public closeFullInventory(): void {
    this.fullInventoryElement.style.display = 'none';
    this.isFullInventoryOpen = false;
    
    // 恢复游戏
    document.body.style.cursor = '';
  }

  public toggleFullInventory(): void {
    if (this.isFullInventoryOpen) {
      this.closeFullInventory();
    } else {
      this.openFullInventory();
    }
  }

  private updateFullInventory(): void {
    if (!this.isFullInventoryOpen) return;

    const slots = this.fullInventoryElement.querySelectorAll('.inventory-slot');
    
    slots.forEach((slotElement, index) => {
      const slot = slotElement as HTMLElement;
      const slotIndex = parseInt(slot.dataset.slotIndex || '0');
      const item = this.inventory.getItem(slotIndex);
      
      if (item) {
        const block = getBlock(item.type);
        slot.innerHTML = `
          <div style="font-size: 8px; text-align: center;">
            ${block.name.substring(0, 6)}<br>
            <span style="font-size: 7px;">${item.count}</span>
          </div>
        `;
        slot.style.background = '#444';
      } else {
        slot.innerHTML = '';
        slot.style.background = '#333';
      }
      
      // 高亮选中的快捷栏槽位
      if (slotIndex < 9 && slotIndex === this.inventory.getSelectedSlot()) {
        slot.style.border = '2px solid #fff';
      } else {
        slot.style.border = '1px solid #666';
      }
    });
  }

  private handleSlotMouseDown(event: MouseEvent, slotIndex: number): void {
    if (event.button !== 0) return; // 只处理左键
    
    const item = this.inventory.getItem(slotIndex);
    if (!item) return;
    
    // 开始拖拽
    this.draggedItem = { item: { ...item }, sourceIndex: slotIndex };
    
    // 创建拖拽元素
    this.createDragElement(item, event);
    
    // 清空原槽位（视觉上）
    const slotElement = event.target as HTMLElement;
    slotElement.style.opacity = '0.5';
    
    event.preventDefault();
  }

  private handleSlotMouseUp(event: MouseEvent, slotIndex: number): void {
    if (!this.draggedItem) return;
    
    // 执行物品移动
    if (slotIndex !== this.draggedItem.sourceIndex) {
      this.moveItemToSlot(this.draggedItem.sourceIndex, slotIndex);
    }
    
    this.endDrag();
    event.preventDefault();
  }

  private handleSlotMouseOver(event: MouseEvent, slotIndex: number): void {
    const slotElement = event.target as HTMLElement;
    
    // 悬停效果
    if (!this.draggedItem) {
      slotElement.style.background = '#555';
    } else {
      // 拖拽时的目标高亮
      slotElement.style.border = '2px solid #4CAF50';
    }
  }

  private handleSlotMouseLeave(event: MouseEvent, slotIndex: number): void {
    const slotElement = event.target as HTMLElement;
    const item = this.inventory.getItem(slotIndex);
    
    // 恢复正常样式
    if (!this.draggedItem) {
      slotElement.style.background = item ? '#444' : '#333';
    }
    
    // 恢复边框
    if (slotIndex < 9 && slotIndex === this.inventory.getSelectedSlot()) {
      slotElement.style.border = '2px solid #fff';
    } else {
      slotElement.style.border = '1px solid #666';
    }
  }

  private createDragElement(item: InventoryItem, event: MouseEvent): void {
    this.dragElement = document.createElement('div');
    const block = getBlock(item.type);
    
    this.dragElement.innerHTML = `
      <div style="font-size: 10px; text-align: center; color: white;">
        ${block.name}<br>
        <span style="font-size: 8px;">${item.count}</span>
      </div>
    `;
    
    this.dragElement.style.cssText = `
      position: fixed;
      width: 35px;
      height: 35px;
      background: #444;
      border: 2px solid #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      pointer-events: none;
      z-index: 3000;
      border-radius: 3px;
    `;
    
    document.body.appendChild(this.dragElement);
    this.updateDragElementPosition(event);
    
    // 监听鼠标移动
    document.addEventListener('mousemove', this.handleMouseMove);
    document.addEventListener('mouseup', this.handleGlobalMouseUp);
  }

  private handleMouseMove = (event: MouseEvent): void => {
    if (this.dragElement) {
      this.updateDragElementPosition(event);
    }
  };

  private handleGlobalMouseUp = (event: MouseEvent): void => {
    this.endDrag();
  };

  private updateDragElementPosition(event: MouseEvent): void {
    if (this.dragElement) {
      this.dragElement.style.left = (event.clientX - 17) + 'px';
      this.dragElement.style.top = (event.clientY - 17) + 'px';
    }
  }

  private moveItemToSlot(fromIndex: number, toIndex: number): void {
    const fromItem = this.inventory.getItem(fromIndex);
    const toItem = this.inventory.getItem(toIndex);
    
    if (!fromItem) return;
    
    if (!toItem) {
      // 目标槽位为空，直接移动
      this.inventory.setItem(toIndex, fromItem.type, fromItem.count);
      this.inventory.setItem(fromIndex, fromItem.type, 0); // 清空原槽位
    } else if (toItem.type === fromItem.type) {
      // 相同物品类型，尝试合并
      const totalCount = fromItem.count + toItem.count;
      if (totalCount <= 64) {
        // 可以完全合并
        this.inventory.setItem(toIndex, fromItem.type, totalCount);
        this.inventory.setItem(fromIndex, fromItem.type, 0); // 清空原槽位
      } else {
        // 部分合并
        this.inventory.setItem(toIndex, fromItem.type, 64);
        this.inventory.setItem(fromIndex, fromItem.type, totalCount - 64);
      }
    } else {
      // 不同物品类型，交换位置
      this.inventory.setItem(fromIndex, toItem.type, toItem.count);
      this.inventory.setItem(toIndex, fromItem.type, fromItem.count);
    }
    
    this.updateFullInventory();
    this.updateHotbar();
  }

  private endDrag(): void {
    // 清理拖拽状态
    if (this.dragElement) {
      document.body.removeChild(this.dragElement);
      this.dragElement = null;
    }
    
    // 移除事件监听器
    document.removeEventListener('mousemove', this.handleMouseMove);
    document.removeEventListener('mouseup', this.handleGlobalMouseUp);
    
    // 恢复所有槽位的透明度
    const slots = this.fullInventoryElement.querySelectorAll('.inventory-slot');
    slots.forEach(slot => {
      (slot as HTMLElement).style.opacity = '1';
    });
    
    this.draggedItem = null;
    this.updateFullInventory();
  }

  private sortInventory(): void {
    // 获取所有非空物品
    const items: { item: InventoryItem; index: number }[] = [];
    
    for (let i = 0; i < 36; i++) {
      const item = this.inventory.getItem(i);
      if (item) {
        items.push({ item, index: i });
      }
    }
    
    // 按物品类型排序
    items.sort((a, b) => {
      const blockA = getBlock(a.item.type);
      const blockB = getBlock(b.item.type);
      return blockA.name.localeCompare(blockB.name);
    });
    
    // 清空物品栏
    for (let i = 0; i < 36; i++) {
      this.inventory.setItem(i, 0 as any, 0);
    }
    
    // 重新放置排序后的物品
    items.forEach((itemData, index) => {
      if (index < 36) {
        this.inventory.setItem(index, itemData.item.type, itemData.item.count);
      }
    });
    
    this.updateFullInventory();
    this.updateHotbar();
    
    // 显示排序完成提示
    this.showNotification('Inventory sorted!');
  }

  private showNotification(message: string): void {
    const notification = document.createElement('div');
    notification.textContent = message;
    notification.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: rgba(76, 175, 80, 0.9);
      color: white;
      padding: 10px 20px;
      border-radius: 5px;
      z-index: 3000;
      font-weight: bold;
      pointer-events: none;
    `;
    
    document.body.appendChild(notification);
    
    // 2秒后移除通知
    setTimeout(() => {
      if (notification.parentNode) {
        document.body.removeChild(notification);
      }
    }, 2000);
  }

  public isFullInventoryVisible(): boolean {
    return this.isFullInventoryOpen;
  }
}